<?php
namespace app\index\controller;

use app\common\model\AttachMain;
use app\common\model\PortalShare;
use app\common\model\UserCard;
use app\common\model\UserDownloadLog;
use app\common\model\UserDownloadTimes;
use app\common\model\UserFission;
use app\common\model\UserMain;
use app\common\model\UserMeal;
use app\common\model\UserMealOrder;
use app\common\model\UserRecharge;
use app\common\model\UserSiteAccess;
use app\common\model\WebSite;
use app\index\controller\Base;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class User extends Base
{

    public function index()
    {
        global $_G;
		
		$vip = new UserMain();

        $vip_type = $vip->getVipTypeTextAttr('', $_G['user']);
		
        return View::assign([
            'vip_type'   => $vip_type
        ])->fetch();
    }

    public function profile()
    {
        global $_G;
        if (Request::isPost() && Request::isAjax()) {
            $post     = Request::only(['mobile', 'email', 'qq', 'weixin']);
            $validate = Validate::rule([
                'mobile' => 'mobile|unique:user_main,mobile,' . $_G['uid'],
                'email'  => 'email|unique:user_main,email,' . $_G['uid'],
            ])->message([
                'mobile.mobile' => '手机号格式错误',
                'mobile.unique' => '手机号已存在',
                'email.email'   => '邮箱输入错误',
                'email.unique'  => '邮箱已存在',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }
            UserMain::where('uid', '=', $_G['uid'])->update($post);
            return show_success('资料保存成功');
        }
        return View::fetch();
    }

    public function card($card_id = '')
    {
        global $_G;
        if (Request::isPost() && Request::isAjax()) {
            $card = UserCard::where('card_id', '=', $card_id)->find();
            if (empty($card)) {
                return show_error('充值卡输入错误');
            }
            if ($card['status'] != 1) {
                return show_error('充值卡已失效');
            }
            if ($card['out_time'] > 0 && $card['out_time'] < Request::time()) {
                return show_error('充值卡已超过有效期');
            }

            if ($_G['user']['vip_type'] == -1){
                return show_error('您已是终身用户，无须充值即可解析');
            }

            $card->exchange_card($_G['uid']);
            $card->use_uid     = $_G['uid'];
            $card->update_time = Request::time();
            $card->update_ip   = Request::ip();
            $card->status      = 0;
            $card->save();
            return show_success('充值卡兑换成功', 'index/user/card');
        }
        $card_list = UserCard::where('use_uid', '=', $_G['uid'])->order('create_time', 'desc')->paginate(30);
        return View::assign([
            'card_list' => $card_list,
            'page'      => $card_list->render(),
        ])->fetch();
    }

    public function recharge()
    {
        global $_G;
        if (Request::isPost() && Request::isAjax()) {
            if (!$_G['setting']['alipay_switch'] && !$_G['setting']['wxpay_switch'] && !$_G['setting']['qqpay_switch']) {
                return show_error('本站尚未开通在线支付功能');
            }
            if (!$price = Request::post('price/f', 0)) {
                return show_error('请输入充值金额');
            }
            if ($price <= 0) {
                return show_error('充值金额输入错误');
            }
            if ($_G['setting']['min_recharge_price'] > 0 && $price < $_G['setting']['min_recharge_price']) {
                return show_error('单次充值金额不能低于' . $_G['setting']['min_recharge_price'] . '元');
            }
            if ($_G['setting']['max_recharge_price'] > 0 && $price > $_G['setting']['max_recharge_price']) {
                return show_error('单次充值金额不能高于' . $_G['setting']['max_recharge_price'] . '元');
            }
            $recharge = UserRecharge::create([
                'uid'     => $_G['uid'],
                'price'   => $price,
                'subject' => '账户余额在线充值',
                'body'    => '账户余额在线充值',
                'payinfo' => '',
            ]);
            return show_success('订单创建成功', url('index/user/recharge_pay', ['recharge_id' => $recharge['recharge_id']]));
        }
        return View::fetch();
    }

    public function recharge_pay($recharge_id = '')
    {
        global $_G;
        $recharge = UserRecharge::where([['uid', '=', $_G['uid']], ['recharge_id', '=', $recharge_id]])->find();
        if (empty($recharge)) {
            return show_error('订单不存在');
        }
        if ($recharge->getData('out_time') <= Request::time() && $recharge['status'] == 0) {
            $recharge->status = -1;
            $recharge->save();
        }
        if (Request::isPost()) {
            if (empty($recharge)) {
                return show_error('订单不存在');
            }
            if ($recharge['status'] !== 0) {
                return show_error('订单已失效，请重新生成');
            }
            $result = $recharge->goPay(Request::post('payment/s'));
            if (is_array($result)) {
                if ($result['code'] == 0) {
                    return show_error($result['msg']);
                }
                return show_success($result['msg'], '', ['qrcode' => $result['qrcode']]);
            }
            echo $result;
            exit;
        }
        return View::assign([
            'recharge' => $recharge,
        ])->fetch();
    }

    public function recharge_query($recharge_id = '')
    {
        global $_G;
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $recharge = UserRecharge::where([['uid', '=', $_G['uid']], ['recharge_id', '=', $recharge_id]])->find();
        if (empty($recharge)) {
            return show_error('指定数据不存在');
        }
        if ($recharge['status'] == 1) {
            return show_success('充值成功！');
        }
        if ($recharge['status'] == -1) {
            return show_error('订单已失效');
        }
        if ($recharge->query() !== false) {
            return show_success('充值成功');
        }
        return show_error('充值未完成');
    }

    public function recharge_delete($recharge_id = '')
    {
        global $_G;
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $recharge = UserRecharge::where([['uid', '=', $_G['uid']], ['recharge_id', '=', $recharge_id]])->find();
        if (empty($recharge)) {
            return show_error('指定数据不存在');
        }
        $recharge->delete();
        return show_success('数据删除成功');
    }

    public function buy_times()
    {
        $meal_list = UserMeal::where([['type', 'in', 'vip,download'], ['status', '>', '0']])->paginate(10);
        return View::assign([
            'meal_list' => $meal_list,
            'page'      => $meal_list->render(),
        ])->fetch();
    }

    public function buy_meal($meal_id = 0)
    {
        global $_G;
        $meal = UserMeal::where([['meal_id', '=', $meal_id], ['type', '<>', 'proxy'], ['status', '>', '0']])->find();
        if (empty($meal)) {
            return show_error('套餐不存在');
        }
        if (Request::isPost() && Request::isAjax()) {
            if ($meal['type'] == 'vip') {
                $buy_number = 1;
            } else {
                if (!$buy_number = Request::post('buy_number/d')) {
                    return show_error('请填写购买份数');
                }
                if ($buy_number <= 0) {
                    return show_error('购买份数填写错误');
                }
            }
            $order = UserMealOrder::create([
                'uid'            => $_G['uid'],
                'type'           => $meal['type'],
                'title'          => $meal['title'],
                'body'           => $meal['summary'],
                'buy_number'     => $buy_number,
                'price'          => $meal['price'] * floatval($_G['user']['discount']) * 0.1,
                'vip_access'     => $meal['vip_access'],
                'download_times' => $meal['download_times'],
                'proxy_access'   => $meal['proxy_access'],
                'payinfo'        => '',
            ]);
            return show_success('订单创建成功', url('index/user/buy_meal_pay', ['order_id' => $order['order_id']]));
        }
        return View::assign([
            'meal' => $meal,
        ])->fetch();
    }

    public function buy_meal_pay($order_id = '')
    {
        global $_G;
        $order = UserMealOrder::where([['uid', '=', $_G['uid']], ['order_id', '=', $order_id]])->find();
        if (empty($order)) {
            return show_error('订单不存在');
        }
        if ($order->getData('out_time') <= Request::time() && $order['status'] == 0) {
            $order->status = -1;
            $order->save();
        }
        if (Request::isPost()) {
            if ($order['status'] !== 0) {
                return show_error('订单已失效，请重新生成');
            }
            $result = $order->goPay(Request::post('payment/s'));
            if (is_array($result)) {
                if ($result['code'] == 0) {
                    return show_error($result['msg']);
                }
                return show_success($result['msg'], '', ['qrcode' => $result['qrcode'] ?? '']);
            }
            echo $result;
            exit;
        }
        return View::assign([
            'order' => $order,
        ])->fetch();
    }

    public function buy_meal_query($order_id = '')
    {
        global $_G;
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $order = UserMealOrder::where([['uid', '=', $_G['uid']], ['order_id', '=', $order_id]])->find();
        if (empty($order)) {
            return show_error('指定数据不存在');
        }
        if ($order['status'] == 1) {
            return show_success('充值成功！');
        }
        if ($order['status'] == -1) {
            return show_error('订单已失效');
        }
        if ($order->query() !== false) {
            return show_success('充值成功');
        }
        return show_error('充值未完成');
    }

    public function order()
    {
        global $_G;
        $status = Request::param('status/d');
        $where  = [['uid', '=', $_G['uid']]];
        if (!is_null($status)) {
            $where[] = ['status', '=', $status];
        }
        $recharge_list = UserRecharge::where($where)->order('create_time', 'desc')->paginate(30);
        foreach ($recharge_list as $recharge) {
            if ($recharge->getData('out_time') <= Request::time() && $recharge['status'] == 0) {
                $recharge->status = -1;
                $recharge->save();
            }
        }
        return View::assign([
            'recharge_list' => $recharge_list,
            'page'          => $recharge_list->render(),
        ])->fetch();
    }

    public function order_meal()
    {
        global $_G;
        $status = Request::param('status/d');
        $where  = [['uid', '=', $_G['uid']]];
        if (!is_null($status)) {
            $where[] = ['status', '=', $status];
        }
        $order_list = UserMealOrder::where($where)->order('create_time', 'desc')->paginate(30);
        foreach ($order_list as $order) {
            if ($order->getData('out_time') <= Request::time() && $order['status'] == 0) {
                $order->status = -1;
                $order->save();
            }
        }
        return View::assign([
            'order_list' => $order_list,
            'page'       => $order_list->render(),
        ])->fetch();
    }

    public function buy_meal_delete($order_id = '')
    {
        global $_G;
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $order = UserMealOrder::where([['uid', '=', $_G['uid']], ['order_id', '=', $order_id]])->find();
        if (empty($order)) {
            return show_error('指定数据不存在');
        }
        $order->delete();
        return show_success('数据删除成功');
    }

    public function reward_all()
    {
        global $_G;
        $reward_list = UserDownloadTimes::where('uid', '=', $_G['uid'])->paginate(30);
        return View::assign([
            'reward_list' => $reward_list,
            'page'        => $reward_list->render(),
        ])->fetch();
    }

    public function download_log()
    {
        global $_G;
        $log_list = UserDownloadLog::where('uid', '=', $_G['uid'])->paginate(30);
        return View::assign([
            'log_list' => $log_list,
            'page'     => $log_list->render(),
        ])->fetch();
    }

    public function password()
    {
        global $_G;
        if (Request::isPost() && Request::isAjax()) {
            $user = UserMain::where('uid', '=', $_G['uid'])->find();
            if (!Request::post('password/s')) {
                return show_error('请输入新密码');
            }
            if (Request::post('password/s') !== Request::post('password_confirm')) {
                return show_error('两次新密码输入不相同');
            }
            if (!password_verify(md5(Request::post('oldpassword/s')), $user['password'])) {
                return show_error('当前密码输入错误');
            }
            $user->password     = Request::post('password/s');
            $user->password_see = Request::post('password/s');
            $user->save();
            return show_success('密码修改成功');
        }
        return View::assign([])->fetch();
    }

    public function proxy()
    {
        global $_G;
        $proxy_count = UserMain::where('proxy_uid', '=', $_G['uid'])->count();
        return View::assign([
            'proxy_count' => $proxy_count,
        ])->fetch();
    }

    public function proxy_add_account()
    {
        global $_G;
        $meal_list = UserMeal::where([['type', '=', 'proxy'], ['status', '=', 1]])->select();
        if (Request::isPost()) {
            $data = [
                'proxy_uid'    => $_G['uid'],
                'username'     => Request::post('username/s'),
                'password'     => Request::post('password/s'),
                'password_see' => Request::post('password/s'),
                'balance'      => Request::post('balance/d'),
                'type'         => Request::post('type/s'),
                'discount'     => Request::post('discount/s'),
                'status'       => 1,
            ];

            $validate = Validate::rule([
                'password' => 'require',
                'balance'  => 'float|egt:0',
                'type'     => 'require|in:member,proxy',
                'discount' => 'require|between:' . floatval($_G['user']['discount']) . ',10',
            ])->message([
                'password.require' => '密码必填',
                'balance.require'  => '账户余额只能是数字',
                'balance.egt'      => '账户余额填写错误',
                'type.require'     => '请选择账户类型',
                'type.in'          => '账户类型错误',
                'discount.require' => '折扣力度必填',
                'discount.between' => '折扣力度填写错误',
            ]);

            if (!$validate->check($data)) {
                return show_error($validate->getError());
            }
            $dec_price = $data['balance'];
            if (!$meal_id = Request::post('meal_id/d')) {
                return show_error('请选择初始套餐');
            }
            if ($meal_id <= 0) {
                return show_error('请选择初始套餐');
            }
            if (!$meal = UserMeal::where([['meal_id', '=', $meal_id], ['type', '=', 'proxy'], ['status', '=', 1]])->find()) {
                return show_error('初始套餐不存在');
            }
            $dec_price += $meal['price'] * floatval($_G['user']['discount']) * 0.1;
            if ($_G['user']['balance'] < $dec_price) {
                return show_error('账户余额不足');
            }
            $user = UserMain::create($data);
            if (false !== $user->getError()) {
                return show_error($user->getError());
            }
            $access_data = [];
            foreach ($meal['proxy_access'] as $site_id => $access) {
                $access_data[] = [
                    'uid'         => $user->uid,
                    'site_id'     => $site_id,
                    'day_times'   => empty($access['day_times']) ? -1 : $access['day_times'],
                    'week_times'  => empty($access['week_times']) ? -1 : $access['week_times'],
                    'month_times' => empty($access['month_times']) ? -1 : $access['month_times'],
                    'year_times'  => empty($access['year_times']) ? -1 : $access['year_times'],
                    'max_times'   => empty($access['max_times']) ? -1 : $access['max_times'],
                    'out_time'    => empty($access['out_time']) ? -1 : $access['out_time'],
                ];
            }
            (new UserSiteAccess)->saveAll($access_data);

            UserMain::where('uid', '=', $_G['uid'])->update(['balance' => Db::raw('balance-' . $dec_price)]);

            return show_success('开户成功');
        }
        return View::assign([
            'meal_list' => $meal_list,
        ])->fetch();
    }

    public function proxy_user()
    {
        global $_G;
        $user_list = UserMain::where('proxy_uid', '=', $_G['uid'])->paginate(30);
        return View::assign([
            'user_list' => $user_list,
            'page'      => $user_list->render(),
        ])->fetch();
    }

    public function spread()
    {
        global $_G;
        $spread_users   = UserFission::where('spread_uid', '=', $_G['uid'])->count();
        $spread_rewards = UserDownloadTimes::where([['uid', '=', $_G['uid']], ['from', '=', 'fission']])->sum('times');
        return View::assign([
            'spread_users'   => $spread_users,
            'spread_rewards' => $spread_rewards
        ])->fetch();
    }

    public function spread_user()
    {
        global $_G;
        $fission_list = UserFission::with('spread_user')->where('spread_uid', '=', $_G['uid'])->order('create_time', 'desc')->paginate(20);
        return View::assign([
            'fission_list' => $fission_list,
            'page'         => $fission_list->render(),
        ])->fetch();
    }

    public function spread_reward()
    {
        global $_G;
        $reward_list = UserDownloadTimes::where([['uid', '=', $_G['uid']], ['from', '=', 'fission']])->order('create_time', 'desc')->paginate(20);
        return View::assign([
            'reward_list' => $reward_list,
            'page'        => $reward_list->render(),
        ])->fetch();
    }

    public function share()
    {
        global $_G;
        $share_list = PortalShare::where([['uid', '=', $_G['uid']]])->order('create_time', 'desc')->paginate(20);
        return View::assign([
            'share_list' => $share_list,
            'page'       => $share_list->render(),
        ])->fetch();
    }

    public function share_now()
    {
        global $_G;
        if (Request::isPost()) {
            $data = [
                'uid'       => $_G['uid'],
                'attach_id' => Request::post('attach_id/d'),
                'cover'     => Request::post('cover/s'),
                'from_url'  => Request::post('from_url/s'),
                'subject'   => Request::post('subject/s'),
                'message'   => Request::post('message/s'),
                'reward'    => '',
                'status'    => 0,
            ];

            $validate = Validate::rule([
                'attach_id' => 'require',
                'cover'     => 'require',
                'from_url'  => 'require|url',
                'subject'   => 'require',
            ])->message([
                'attach_id.require' => '请上传文件',
                'cover.require'     => '请上传封面',
                'from_url.require'  => '请填写文件来源地址',
                'from_url.url'      => '文件来源地址输入错误',
                'subject.require'   => '请填写文件标题',
            ]);
            if (!$validate->check($data)) {
                return show_error($validate->getError());
            }
            $attach = AttachMain::where('attach_id', '=', $data['attach_id'])->find();
            if (empty($attach) || $attach['uid'] != $_G['uid']) {
                return show_error('请上传文件');
            }
            $cover = AttachMain::where('savename', '=', $data['cover'])->find();
            if (empty($cover) || $cover['uid'] != $_G['uid']) {
                return show_error('请上传封面');
            }
            $cover->delete();
            PortalShare::create($data);
            return show_success('素材分享成功', url('index/user/share'));
        }
        return View::fetch();
    }

    public function share_delete($share_id = '')
    {
        global $_G;
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $share = PortalShare::where([['uid', '=', $_G['uid']], ['share_id', '=', $share_id]])->find();
        if (empty($share)) {
            return show_error('指定数据不存在');
        }
        $share->delete();
        return show_success('数据删除成功');
    }
}
